#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

#define NUM 10000
#define CPU 5
#define CPU_NUM (NUM/CPU)

struct param {
    int start;
    int end;
};

struct result {
    double sum;
};

void *compute(void *arg)
{
    struct param *param;
    struct result *result;
    double pi = 0;
    param = (struct param *)arg;
    for (int i = param->start; i < param->end; i++) {
        double t = 1 / (double)(2 * (i + 1) - 1);
        if (i % 2 == 1) {
            pi -= t;
        }
        else
            pi += t;
    }
    pi *= 4;
    result = malloc(sizeof(struct result));
    result->sum = pi;
    return result;
}

int main()
{
    pthread_t workers[CPU];
    struct param params[CPU];
    int i;
    for (i = 0; i < CPU; i++) {
        struct param *param;
        param = &params[i];
        param->start = i * CPU_NUM;
        param->end = (i + 1) * CPU_NUM;
        pthread_create(&workers[i], NULL, compute, param);
    }
    double pi = 0;
    for (i = 0; i < CPU; i++) {
        struct result *result;
        pthread_join(workers[i], (void **)&result);
        pi += result->sum;
        free(result);
    }
    printf("%f\n", pi);
    return 0;
}
